/**
 * Created by yangfan on 2016/9/18.
 */
//"business/home/directives/uploadDirective",
define(["require",'config/appregister',"i18n","config/uploadFile","business/services/httpServices","business/services/constant","business/services/utils",
    "business/home/directives/editorDirective","business/services/fileuploader"
    ],function(require,app,i18n,uploadFile,httpService,constant,unitil){
    app.controller('uploadSelectFileCtrl',function($scope,$state){
    	//标签
    	$scope.tags2 = [//ngInputTab自己写方法

        ];
        $scope.controlLength = function(str){
            var l = str.length;
            var blen = 0;
            for(var i=0; i<l; i++) {
                if (str.charCodeAt(i) > 255) {
                    blen ++;
                }
                blen ++;
            }
            if(blen == 32){
                var maxLength = $scope.tagsWork.length;
            }
            if(blen > 32){
                $scope.tagsWork.length = maxLength;
            }
        }
        $scope.saveTagsname=function(a){
            if(a == ''){
                return;
            }
        	if($scope.tags2.length == 6){
        		alert('最多只能添加六个标签哦，亲');
        		return;
        	}
            if($scope.tags2.indexOf(a) != -1){
                alert("福利不能相同哦")
            }else{
                $scope.tags2.push(a);
                $scope.tagsWork = '';
            }
        }
        $scope.deleteInput=function($index){
            $scope.tags2.splice($index,1);
        }

    	
    	
        $scope.isDetailPage = false;
        $scope.isMainpage = true;
        $scope.showFillInfo = true;
        $scope.i18n = i18n;
        $scope.mainData = {
            logoSrc:"them/images/gcj_big_logo.png"
        };
        $scope.showTemplate = {
            isSelectFile:false,
            isUploadFile:true,
            showFillLeftL:false
        };
        $scope.fillInfo = "您已成功上传1份文件 ， 失败0份";
        $scope.successNoticeInfo = "您已成功上传1个文件，审核通过后，将获得 5 E币";
        $scope.uploadFileName = "";
        $scope.uploadNoticeInfo = "";

        //多文件上传时用于判断文件类型
        $scope.currentFileType = "";
        $scope.goTo = function(state){
            if(state == 'eng.uploadSelectFile'){
                $state.transitionTo(state, {}, {
                    reload: true, inherit: false, notify: true
                });
            }else{
                $state.go(state);
            }
        };

        //文件上传参数
        $scope.uploadInfo  = {
            typeId:"",
            tcId:"",
            scId:"",
            name:"",
            size:"",
            tagsId:"",
            price:10,
            path:"",
            introduction:"",
            dcIds:"",
            labels:""
        };
        //隐藏二级目录
        $scope.isShowSec = false;
        //获取文件格式
        function getFileType(){
            var reqFile = {
                type: "GET"
            };
            httpService.getFileType(reqFile).success(function (response) {
                $scope.fileType = response.data;
                console.log(response.data)
            });
        }
        getFileType();
        //单文件时 上传文件
        function uploadInfo (){
            //todo 先校验必选项是否全部输入
            // 判断文件类型
            var file = $scope.upload.file;
            if(!file.name){
               return
            }
            var fileName = file.name.toLowerCase();
            $scope.uploadFileName = fileName;
           /* var type = fileName.substr(fileName.lastIndexOf(".")+1);*/
            var type = unitil.getFileType(file.ext);
            var fileTypeId;
            if(type == "docx"){
                type = "doc";
            }
            for(var i = 0;i < $scope.fileType.length;i++){
                if($scope.fileType[i].typeName == type){
                    fileTypeId = $scope.fileType[i].typeId;
                }
            }
            /*switch (type){
                case "word":
                    fileTypeId = 1;
                    break;
                case "xls":
                    fileTypeId = 2;
                    break;
                case "ppt":
                    fileTypeId = 3;
                    break;
                case "cad":
                    fileTypeId = 4;
                    break;
                case "pdf":
                    fileTypeId = 5;
                    break;
                case "other":
                    fileTypeId = 20;
                    break;
            }*/

            var size = file.size;

            //获取dcId
            if(!$scope.uploadInfo.scId){
                return;
            }
            //如果当前为国际分类 获取dcId集合
            var arr = [],dcId;
            if($scope.uploadInfo.tcId ==2){
                if($scope.interDcIds.major){
                    arr.push($scope.interDcIds.major)
                }
                if($scope.interDcIds.content){
                    arr.push($scope.interDcIds.content)
                }
                if($scope.interDcIds.projectPattern){
                    arr.push($scope.interDcIds.projectPattern)
                }
                if($scope.interDcIds.manage){
                    arr.push($scope.interDcIds.manage)
                }
                dcId = arr.join(",");
            }else{
                dcId =$scope.uploadInfo.dcIds;
            };
            if($scope.upload.file.path==""){
                return
            }
            var path = $scope.upload.file.path;
            if($scope.tags2 == []){
                return;
            }
            //判断用户是否已经输入 若非 则不执行添加文件请求
            if(!$scope.uploadInfo.tcId||!$scope.uploadInfo.scId||!$scope.uploadInfo.name||!$scope.uploadInfo.price){
                return;
            }
            var requestion = {
                type:"POST",
                uri:"add",
                data:{
                    tags:$scope.tags2 ==[] || ""?$scope.tags2:$scope.tags2.join(',')
                }
            };

            //shit code !
            var req = {
                type:"POST",
                uri:"add",
                data:{
                    typeId:fileTypeId,
                    tcId:$scope.uploadInfo.tcId,
                    scId:$scope.uploadInfo.scId,
                    name:$scope.uploadInfo.name,
                    size:size,
                    tagIds: '',
                    price:$scope.uploadInfo.price,
                    path:path,
                    introduction:$scope.uploadInfo.introduction,
                    dcIds:dcId,
                    mold:0
                }
            };
            if($scope.tags2 == [] || ""){
                return;
            }
            if(!!$scope.tags2){
                httpService.tagServices(requestion).success(function(response){
                    $scope.uploadInfo.labelIds = response.data.join(",");
                    req.data.tagIds = response.data.join(",");
                    addFileByPost(req)
                }).error(function(){})
            }else{
                addFileByPost(req)
            }

        }
        //获取一二级资料目录
        function getTopCategory(){
            var requestion = {
                type: "GET",
                param: "getTopCategory"
            };
            httpService.getTopCategory(requestion).success(function (response) {
                if (response.msg !== "success") {
                    return
                }
                //  得到 一级分类 分类名
                $scope.engClassify = response.data;
                console.log("一级分类");
                console.log($scope.engClassify);
            }).error(function () {
                console.log("请求失败！");
            });
        }

        //获取二级目录资料分类
        function getSecCategory(tcId){
            var req2 = {
                type: "GET",
                tcId: tcId,
                param: 'getSecondaryCategory'
            };

            httpService.getSecondCategory(req2).success(function (response) {
                if (response.data) {
                    $scope.$apply(function(){
                       // $scope.isShowSec = true;
                        $scope.secCate = response.data;
                    })
                }
            });
        }

        //获取三级目录资料分类
        function getDetailCategory(scId){
            if(!$scope.uploadInfo.tcId) return;
            var req3 = {
                type: "GET",
                data: {
                    scId: scId,
                    tcId: $scope.uploadInfo.tcId
                },
                param: 'getDetailCategory'
            };
                httpService.getDetailCategory(req3).success(function (response) {
                    if(response.data){
                        $scope.$apply(function(){

                            // 根据国际 国内不同 显示两种不同的select 选择框
                            if($scope.uploadInfo.tcId == 1){
                                $scope.isShowNationDec = true;
                            }else if($scope.uploadInfo.tcId ==2){
                                $scope.isShowInterDec = true;
                            }
                            $scope.curDetail = response.data;
                        })
                    }
                }).error(function (response) {
                })
        }

        //点击确认 上传文件信息
        function addFileByPost(req){
             httpService.addFile(req).success(function(response){

                 $scope.$apply(function(){
                     $scope.coinValue = 0;
                     if(response.data){
                         $scope.coinValue = response.data.coinValue
                     }
                     $scope.showFillInfo = false;
                 });
             }).error(function(){
                 $scope.uploadNoticeInfo = "文件上传失败";
             })
        }

        //初始化一级目录分类
        getTopCategory();

        // TopCategory options  change事件
        var backgroundObj = {
            background:"#00A4FF",
            color:"#fff"
        };
        $scope.changeTcOptions = function(item,index){
            $scope.isCheckForTc = [];
            $scope.isCheckForSc = [];
            $scope.isCheckForDc = [];
            $scope.isCheckForTc[index] = backgroundObj ;

            $scope.interDcIds= {
                major:"",
                content:"",
                projectPattern:"",
                manage:""
            };
            if(item.tcId == 1){
                $scope.isShowSec = true;
                $scope.isShowNationDec = false;
                $scope.isShowInterDec = false;
            }else{
                $scope.isShowSec = false;
                $scope.isShowInterDec = true;
            }
            $scope.uploadInfo.dcIds = "";
            $scope.uploadInfo.scId = [];
            $scope.uploadInfo.tcId = item.tcId;
            getSecCategory(item.tcId)  ;
        };

        // SecCategory options  change事件
        $scope.changeScOptions = function(item,index){

            $scope.isCheckForSc = [];
            $scope.isCheckForDc = [];
            $scope.isCheckForSc[index] = backgroundObj ;

            if(!item)return;
            if(item.scName == "项目管理"){
                $scope.major1 = '专业';
                $scope.major2 = '内容';
                $scope.major3 = '项目模式';
            }else if(item.scName == "技术规范"){
                $scope.major1 = '国家';
                $scope.major2 = '专业';
                $scope.major3 = '种类';
            }else if(item.scName == "国际商务"){
                $scope.major1 = '经济环境';
                $scope.major2 = '法律法规';
                $scope.major3 = '宗教文化';
                $scope.major4 = '合同管理';
            }
            if(item.tcId ==1){
                $scope.isShowNationDec = true;
            }else{
                $scope.isShowInterDec = true;
                if(typeof index == 'number'){
                    $scope.showInterDecCate = [];
                    $scope.showInterDecCate[index] = true;
                }
            }
            $scope.interDcIds= {
                major:"",
                content:"",
                projectPattern:"",
                manage:""
            };
            $scope.uploadInfo.dcIds = "";
            $scope.uploadInfo.scId = item.scId;
            getDetailCategory(item.scId);
        };

        //国内时， 三级分类change 事件
        $scope.changeDcOptions = function(item ,index){

            $scope.isCheckForDc = [];
            $scope.isCheckForDc[index] = backgroundObj ;
            if(!item) return ;
            $scope.uploadInfo.dcIds = item.dcId;
        };
        $scope.showInterDecCate = [];

        //select 复选框设置
        var expanded = false;
        $scope.showCheckboxes = function(){
            var checkboxes = document.getElementById("checkboxes");
            if (!expanded) {
                checkboxes.style.display = "block";
                expanded = true;
            } else {
                checkboxes.style.display = "none";
                expanded = false;
            }
        };

        // 获取国际情形下 三级分类复选 选中的id数组
        $scope.interDc = [];
        $scope.interDcIds= {
            major:"",
            content:"",
            projectPattern:"",
            manage:""
         };
        $scope.changeCheckbox = function(event,item){
            if(!item){
                return ;
            }

            //如果选中 则插入
            if(event.target.checked){
                if($scope.interDc.indexOf(item.dcId)==-1){
                    $scope.interDc.push(item.dcId);
                }
            }

            // 如果取消选中 则从数组中移除
            if(!event.target.checked){
                var index = $scope.interDc.indexOf(item.dcId);
                if(index!=-1){
                    $scope.interDc.splice(index, 1);
                }
            }
            $scope.uploadInfo.dcIds =  $scope.interDc;
        };

        $scope.addFile = function(){
            uploadInfo();
        };

        $scope.editFileInfo = function(){
                $scope.showTemplate.showFillLeftL = !$scope.showTemplate.showFillLeftL;
                if($scope.editSrc == $scope.src.V){
                    $scope.editSrc = $scope.src.A;
                }else{
                    $scope.editSrc = $scope.src.V;
                }
        };
        $scope.src = {
            V:"them/images/V_logo.png",
            A:"them/images/A_logo.png"
        };
        $scope.editSrc = $scope.src.V;
        $scope.upload = {
            url:'http://101.37.82.219:8087',
            api:constant.config.CONSTANT_UPLOADER,
            path:"",
            file:"",
            onchange:function(){
                //$scope.$apply(function(){
                //    $scope.showTemplate.isSelectFile = true;
                //    $scope.showTemplate.isUploadFile = false;
                //});
            }
        };

        $scope.$on("uploadSuccess",function(data){
            $scope.$apply(function(){
                $scope.showTemplate.isSelectFile = true;
                $scope.showTemplate.isUploadFile = false;
            })
        })
    })
});

